package com.tl.branchmanagementdemo.config;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tl
 */
@Configuration
public class ReturnValueConfig {

    @Resource
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @Bean
    public void init() {
        List<HandlerMethodReturnValueHandler> previousList = requestMappingHandlerAdapter.getReturnValueHandlers();
        if (CollectionUtils.isEmpty(previousList)) {
            return;
        }
        List<HandlerMethodReturnValueHandler> newlist = new ArrayList<>(previousList.size());

        for (HandlerMethodReturnValueHandler returnValueHandler : previousList) {
            if (returnValueHandler instanceof RequestResponseBodyMethodProcessor) {
                newlist.add(new ReturnValueHandler(returnValueHandler));
            } else {
                newlist.add(returnValueHandler);
            }
        }
        requestMappingHandlerAdapter.setReturnValueHandlers(newlist);
    }
}

class ReturnValueHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler handlerMethodReturnValueHandler;

    public ReturnValueHandler(HandlerMethodReturnValueHandler handlerMethodReturnValueHandler) {
        this.handlerMethodReturnValueHandler = handlerMethodReturnValueHandler;
    }

    /**
     * 返回true，则进入handle
     *
     * @param returnType
     * @return
     */
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return true;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        handlerMethodReturnValueHandler.handleReturnValue(returnValue + "=====", returnType, mavContainer, webRequest);
    }
}
